package com.tangkun.environment.fragment.news;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.activity.WebZiXunActivity;
import com.tangkun.environment.adapter.XinWenAdapter;
import com.tangkun.environment.entity.xinwen.MarqueetReturn;
import com.tangkun.environment.entity.xinwen.NewsReturn;
import com.tangkun.environment.fragment.BaseFragment;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxFragmentHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.view.CustomListView;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 新闻Fragment
 */

public class XinWenFragment extends BaseFragment implements CustomListView.OnLoadMoreListener, CustomListView.OnRefreshListener {

    @BindView(R.id.rollviewpager)
    RollPagerView mRollPagerView;
    @BindView(R.id.custom_list_view)
    CustomListView customListView;

    /**
     * 广告轮播图集合
     */
    private List<MarqueetReturn.ResultBean> marqueetList = new ArrayList<MarqueetReturn.ResultBean>();
    /**
     * 广告轮播图适配器
     */
    private XinWenFragment.RollviewpagerAdapter rollviewpagerAdapter;

    public int page = 1;// 当前页
    private int totalCount = 0;// 总数量
    private boolean OnHeadRefreshTAG = true;// 为true时清楚已有数据

    /**
     * 新闻type 全部的时候type为空，不当做参数上传
     */
    private String type = "";
    /**
     * 数据源
     */
    private List<NewsReturn.ResultBean.ListBean> dataList = new ArrayList<NewsReturn.ResultBean.ListBean>();
    /**
     * 适配器
     */
    private XinWenAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_xinwen, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        return view;
    }

    private void initView() {

        /*** 轮播图设置 ***/
        //轮播间隔时间
        mRollPagerView.setPlayDelay(3000);
        //动画时间
        mRollPagerView.setAnimationDurtion(500);
        //设置指示器颜色
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), getResources().getColor(R.color.common_green), getResources().getColor(R.color.common_bg)));

        customListView.setOnRefreshListener(this);
        customListView.setOnLoadListener(this);
        customListView.setCanLoadMore(true);
        customListView.setAutoLoadMore(true);
        adapter = new XinWenAdapter(getActivity(), dataList);
        customListView.setAdapter(adapter);
    }

    private void initData() {
        queryIndexMarquee();
        queryIndexNews();
    }

    /**
     * 获取首页轮播图
     */
    private void queryIndexMarquee() {
        fromNetwork.queryIndexMarquee().compose(new RxFragmentHelper<MarqueetReturn>().ioMain(getActivity(), XinWenFragment.this, true))
                .subscribe(new MySubscribe<MarqueetReturn>(getActivity(), true) {
                    @Override
                    protected void success(MarqueetReturn marqueetListReturn) {
                        if (marqueetListReturn != null) {
                            if (marqueetListReturn.data != null) {
                                marqueetList = marqueetListReturn.data;
                                //刷新广播轮播图
                                rollviewpagerAdapter = new RollviewpagerAdapter(marqueetList);
                                mRollPagerView.setAdapter(rollviewpagerAdapter);
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage + "");
                    }
                });
    }

    @Override
    public void onRefresh() {
        page = 1;
        OnHeadRefreshTAG = true;
        customListView.setCanLoadMore(true);
        queryIndexNews();
    }

    @Override
    public void onLoadMore() {
        OnHeadRefreshTAG = false;
        if (page * pageSize < totalCount) {
            page++;
            queryIndexNews();
        } else {
            customListView.onLoadMoreCompleteNoData();
        }
    }

    /**
     * 新闻列表
     */
    private void queryIndexNews() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNumber", page + "");
        map.put("pageSize", pageSize + "");
        if (!TextUtils.isEmpty(type))
            map.put("type", type);
        fromNetwork.queryIndexNews(map).compose(new RxFragmentHelper<NewsReturn>().ioMain(getActivity(), XinWenFragment.this, true))
                .subscribe(new MySubscribe<NewsReturn>(getActivity(), true) {
                    @Override
                    protected void success(NewsReturn resultBean) {
                        if (resultBean != null) {
                            if (resultBean.data != null) {
                                if (resultBean.data.list != null) {
                                    customListView.onLoadMoreComplete();
                                    customListView.onRefreshComplete();
                                    customListView.setCanLoadMore(true);
                                    totalCount = resultBean.data.totalRow;
                                    if (page * pageSize >= totalCount) {
                                        customListView.setCanLoadMore(false);
                                    }
                                    //下拉刷新
                                    if (OnHeadRefreshTAG) {
                                        OnHeadRefreshTAG = false;
                                        dataList.clear();
                                    }
                                    //填充数据
                                    dataList.addAll(resultBean.data.list);
                                    //刷新列表
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage + "");
                    }
                });
    }


    /**
     * 智能预警首页轮播图片的适配器
     */
    private class RollviewpagerAdapter extends StaticPagerAdapter {

        private List<MarqueetReturn.ResultBean> marqueetList = new ArrayList<MarqueetReturn.ResultBean>();

        public RollviewpagerAdapter(List<MarqueetReturn.ResultBean> marqueetList) {
            this.marqueetList = marqueetList;
        }

        @Override
        public View getView(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(container.getContext());
            //轮播图网络地址
            String imageUrl = GlobalUrl.IMG_URL + marqueetList.get(position).img;
            Glide.with(getActivity())
                    .load(imageUrl)
                    .placeholder(R.mipmap.ic_banner_error)
                    .centerCrop()
                    .into(imageView);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            //轮播图点击事件
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), WebZiXunActivity.class);
                    String id = marqueetList.get(position).newsid;//链接地址
                    intent.putExtra("id", id);
                    JumpHelper.jump(getActivity(), intent, false);
                }
            });
            return imageView;
        }


        @Override
        public int getCount() {
            return marqueetList.size();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //接受到新闻类别改变，刷新新闻列表
    @Subscriber(tag = "XinWenFragment.refreshNews")
    private void refreshNews(Intent intent) {
        type = intent.getStringExtra("type");
        onRefresh();
    }
}
